﻿using Cofe.Core.Property;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Cofe.Core.Utils
{
    public enum EntryComparationMode { ParsePath, Name }
    public class EntryComparer : IComparer<IPropertyProvider>, IComparer<IPropertyHost>, IComparer<ICofeSystemInfo>
    {
        public static EntryComparer CompareParsePath
            = new EntryComparer() { ComparationMode = EntryComparationMode.ParsePath };

        public static EntryComparer CompareName
            = new EntryComparer() { ComparationMode = EntryComparationMode.Name };

        internal EntryComparer() { }
        public EntryComparationMode ComparationMode { get; private set; }
        private static NaturalSorting.NaturalComparer nc = new NaturalSorting.NaturalComparer();

        public int Compare(IPropertyProvider x, IPropertyProvider y)
        {
            switch (ComparationMode)
            {
                case EntryComparationMode.ParsePath:
                    string xPath = x.GetOnePropertyAsync(CofeProperties.FullParseName).Result.ValueAsString;
                    string yPath = y.GetOnePropertyAsync(CofeProperties.FullParseName).Result.ValueAsString;                        
                    return xPath.CompareTo(yPath);
                case EntryComparationMode.Name:
                    string xName = x.GetOnePropertyAsync(CofeProperties.Name).Result.ValueAsString;
                    string yName = y.GetOnePropertyAsync(CofeProperties.Name).Result.ValueAsString;                        
                    return nc.Compare(xName, yName);

                default: throw new NotSupportedException();
            }
        }

        public int Compare(IPropertyHost x, IPropertyHost y)
        {
            return Compare(x.PrimaryPropertyProvider, y.PrimaryPropertyProvider);
        }

        public int Compare(ICofeSystemInfo x, ICofeSystemInfo y)
        {
            return Compare(x.Properties, y.Properties);
        }
    }
}
